package com.gitee.hifong45;

import java.io.Serializable;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

public class Ret<T> implements Serializable {
	
	private static final long serialVersionUID = -2695454088200845652L;

	/**
	 * 结果码
	 */
    private Integer code;

	/**
	 * 结果信息。一般提供失败信息。
	 */
	private String msg;

	/**
	 * 结果数据。一般包含成功数据。
	 */
    private T data;

	/**
	 * 消息生成时间
	 */
	private String tm = DateUtil.now();

    public Ret() {}
    
	public Ret(int _code, String _msg, T _data) {
		this.setCode(_code);
		this.setMsg(_msg);
		this.setData(_data);
	}
    
	public static<T> Ret<T> Ok() { return new Ret<T>(200, "Success", null); }
	public static<T> Ret<T> Ok(T data) { return new Ret<T>(200, "Success", data); }
	
	public static <T> Ret<T> Fail(Msg errorMsg) {
		return new Ret<T>(errorMsg.code, errorMsg.msg, null);
	}
	public static <T> Ret<T> Fail(Msg errorMsg, String extMsg) {
		return new Ret<T>(errorMsg.code, errorMsg.msg + " : " + extMsg, null);
	}
	public static <T> Ret<Object> Fail(Ret<T> result) {
		return new Ret<Object>(result.getCode(), result.getMsg(), null);
	}
	public static <T> Ret<T> Fail(String[] codeMsg) {
		return new Ret<T>(Integer.valueOf(codeMsg[0]), codeMsg[1], null);
	}
	public static <T> Ret<T> Fail(String[] codeMsg, String extMsg) {
		return new Ret<T>(Integer.valueOf(codeMsg[0]), codeMsg[1] + " : " + extMsg, null);
	}
	public static<T> Ret<T> Fail(int code, String msg) {
		return new Ret<T>(code, msg, null);
	}
	
	public static Ret<Kv> str2Ret(String str) {
		return JSONUtil.toBean(str, new TypeReference<Ret<Kv>>() {}, false);
	}
	
	@Override
	public String toString() {
		return StrUtil.format("code: {}, msg: {}, data: {}, tm: {}", code, msg, data, tm);
	}

	public String toJsonStr() {
		return JSONUtil.toJsonStr(this);
	}

	public Integer getCode() {
		return code;
	}

	public String getMsg() {
		return msg;
	}

	public T getData() {
		return data;
	}

	public String getTm() {
		return tm;
	}

	public void setTm(String tm) {
		this.tm = tm;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public void setMsg(String message) {
		this.msg = message;
	}

	public void setData(T data) {
		this.data = data;
	}
}
